package cn.edu.cug.cs.gtl.apis.ui.mapuis;

import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.UIApp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JComponent;

import org.apache.hadoop.fs.FSDataInputStream;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapPane;

public class Map2dUIApp extends UIApp {

    JMapPane mapPane = new JMapPane();

    public JComponent initializeUI() {
        return mapPane;
    }

    public void redrawShpUI(FSDataInputStream fis) throws IOException {
        // 将FSDataInputStream写入临时文件
        File tempFile = File.createTempFile("shapefile", ".shp");
        tempFile.deleteOnExit();

        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        }
        // 使用GeoTools读取临时文件
        FileDataStore store = FileDataStoreFinder.getDataStore(tempFile);
        if (store == null) {
            throw new IOException("Could not open the shapefile");
        }

        SimpleFeatureSource featureSource = store.getFeatureSource();

        MapContent map = new MapContent();
        map.setTitle("二维地图显示");
        Style style = SLD.createSimpleStyle(featureSource.getSchema());
        Layer layer = new FeatureLayer(featureSource, style);
        map.addLayer(layer);

        mapPane.removeAll();
        mapPane.setMapContent(map);

        mapPane.revalidate();
        mapPane.repaint();
    }

    public boolean isValid() {
        return false;
    }

    public UIApp.Type getType() {
        return Type.MAP2D_UI_APP;
    }

    public Map2dUIApp(AbstractApplication theApp) {
        super(theApp);
    }
}
